import { useMemo } from "react";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DownOutlined,
} from "@ant-design/icons";
import { Layout, Button, theme, Dropdown, Space, Avatar } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { setCollapsed } from "@/store/modules/app";
import AppBreadCrumb from "@/layouts/components/AppBreadCrumb";
import { useNavigate, useLocation } from "react-router-dom";
import store from "store2";
import { setLoginState, setAdminUserInfo } from "@/store/modules/admin";
const { Header } = Layout;

export default function AppHeader() {
  const collapsed = useSelector((state) => state.appSlice.collapsed);
  const { adminname } = useSelector((state) => state.adminSlice.adminUserInfo);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  const items = [
    {
      key: "/setting",
      label: <span>设置</span>,
    },
    {
      key: "/account/userlist",
      label: <span>用户</span>,
    },
    {
      key: "/logout",
      label: <span>退出</span>,
    },
  ];
  const onClick = ({ key }) => {
    if (key === "/logout") {
      store.remove("users");
      dispatch(setLoginState(false));
      dispatch(setAdminUserInfo({}));
      navigate(`/login?r=${pathname}`);
    } else {
      navigate(key);
    }
  };
  const changeColor = useMemo(() => { 
    return "#"+Math.floor(Math.random() * 0xffffff)
                    .toString(16)
                    .padEnd(6, "0")
  }, [])
  const changeAvatar = useMemo(
    () => adminname.slice(0, 1).toUpperCase(),
    [adminname]
  );
  return (
    <Header
      style={{
        padding: 0,
        background: colorBgContainer,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        paddingRight: "30px",
      }}
    >
      <Button
        type="text"
        icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        onClick={() => dispatch(setCollapsed(!collapsed))}
        style={{
          fontSize: "16px",
          width: 64,
          height: 64,
        }}
      />
      <AppBreadCrumb />
      <Dropdown
        menu={{
          items,
          onClick,
        }}
      >
        <span style={{ cursor: "pointer" }}>
          <Space>
            <Avatar
              style={{
                backgroundColor: changeColor,
              }}
            >
              {changeAvatar}
            </Avatar>
            {adminname}
            <DownOutlined />
          </Space>
        </span>
      </Dropdown>
    </Header>
  );
}
